#include "qthemeablewidget.h"
#include "controller.h"
#include "feats/thememanager.h"

#include <QPainter>
#include <QPainterPath>
#include <QMouseEvent>

QThemeableDialog::QThemeableDialog(QWidget *parent) :
    QDialog(parent)
{
    _status = Idle;
    applyTheme();
}

void QThemeableDialog::applyTheme()
{
    setWindowFlags(Qt::FramelessWindowHint);

    QString theme = Controller::settings()->value("last_theme", "default").toString();
    ThemeManager::applyTheme(theme, this);
}

void QThemeableDialog::paintEvent(QPaintEvent *e)
{
    Q_UNUSED(e);

    qreal opacity = Controller::settings()->value("view_opacity", "0.8").toDouble();
    int roundness = Controller::settings()->value("view_roundness", "8").toInt();

    QRect widget_rect = this->rect();
    widget_rect.adjust(-1,-1,+1,+1);

    QPainter painter(this);
    QPen pen = Qt::gray;
    pen.setCosmetic(true);

    painter.save();
    //painter.setRenderHint(QPainter::Antialiasing);
    painter.setPen(pen);


    // clip
    QPainterPath rounded_rect;
    //rounded_rect.addRoundRect(1, 1, widget_rect.width() - 2, widget_rect.height() - 2, roundness, roundness);
    rounded_rect.addRoundedRect(widget_rect, roundness, roundness, Qt::AbsoluteSize);
    painter.setClipPath(rounded_rect);

    // get clipping region
    QRegion maskregion = painter.clipRegion();

    // mask the widget
    setMask(maskregion);
    painter.setOpacity(opacity);

    // border
    //painter.drawPath(rounded_rect);

    // restore painter
    painter.restore();
}

void QThemeableDialog::mousePressEvent(QMouseEvent* e)
{
    _status = Moving;
    _origin = e->pos();
}

void QThemeableDialog::mouseReleaseEvent(QMouseEvent* e)
{
    Q_UNUSED(e)
    _status = Idle;
}

void QThemeableDialog::mouseMoveEvent(QMouseEvent* e)
{
    if ( _status == Moving )
        move(pos() + e->pos() - _origin);
}
